﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;


namespace YGame.Base
{
	public class BaseMessage
	{
		public string MessageID { get; set; }
		public string Body { get; set; }

		public BaseMessage()
		{
			//MessageID = GetType().FullName;
		}

		public string Pack()
		{
			return ToJson();
		}

		public void Unpack(string data)
		{
			//this = FromJson(data, GetType());
		}


		public static BaseMessage Create(byte[] data)
		{
			string strJson = System.Text.Encoding.UTF8.GetString(data);
			BaseMessage msg = FromJson(strJson, typeof(BaseMessage)) as BaseMessage;
			msg.Body = strJson;


			return msg;
		}

		public static object FromJson(string strJson, Type type)
		{
			DataContractJsonSerializer ds = new DataContractJsonSerializer(type);
			MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));

			return ds.ReadObject(ms);
		}


		public string ToJson()
		{
			DataContractJsonSerializer ds = new DataContractJsonSerializer(this.GetType());
			using (MemoryStream ms = new MemoryStream())
			{
				ds.WriteObject(ms, this);
				return Encoding.UTF8.GetString(ms.ToArray());
			}
		}


	}
}
